<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class Base extends Model
{
    protected $guarded = [
        'id'
    ];
    //国际化语言
    protected $lang = [];
    public function __construct(){
        $this->lang = config('lang.NATION');
    }
    //批量添加数据
    protected function addAll($data=array()){
        try {
            $res = DB::table($this->getTable())->insert($data);
            return $res;
        }catch (\Exception $e){
            return false;
        }
    }

    //数据分页
    public function paging($model,$page,$limit,$lang='zn'){
        try{
            $offset = ($page-1) * $limit;
            $total =  $model->count();  //获取模型总数据条数
            $result = $model->offset($offset)->limit($limit)->get()->toArray();
            $data = array(
                'total'=>$total,
                'list'=>$result
            );
            return [
                'code'=>0,
                'data'=>$data
            ];
        }catch (\Exception $e){
            return [
                'code'=>1,
                'message'=>$this->lang['ERROR'][$lang]
            ];
        }
    }

    //登录token生成方法
    protected function setToken($key,$expire=360000){
        $time = time();
        $data = ['key'=>$key,'expire'=>$time+$expire];
        $token = encrypt($data);
        return $token;
    }

    //根据用户模型和商品ID获取等级ID和商品折扣
    public function getProdDiscount($user,$proid = 0){
        $total = $user->total;
        $levid = (new UserLevel())->where([
            ['min','<=',$total],['max','>',$total]
        ])->value('id');
        if($levid){
            if($proid){
                $discount = (new ProdDiscount())->where([
                    ['levid','=',$levid],['proid','=',$proid]
                ])->value('discount');
                if($discount){
                    return [
                        'levid'=>$levid,
                        'discount'=>$discount
                    ];
                }else{
                    return [
                        'levid'=>$levid,
                        'discount'=>100
                    ];
                }
            }else{
                return [
                    'levid'=>$levid,
                    'discount'=>100
                ];
            }
        }else{
            return [
                'levid'=>0,
                'discount'=>100
            ];
        }
    }

}
